import subprocess
import io
import logging
import os
import subprocess
import tempfile
from collections.abc import Generator
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from pathlib import Path
from typing import Literal


import pandas as pd

import uvicorn
from docx import Document
from fastapi import FastAPI

from starlette.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from exception.all_exception import global_exception_handlers
from web.chat_web import chat

from web.conversation_web import conversation
from web.file_web import file

from web.testcase_web import testcase


def create_app():
    _app = FastAPI(
        title="digital portrait service",
        version="v1.0.1",
        # 全局以及自定义异常捕获
        exception_handlers=global_exception_handlers
    )
    _app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 添加路由
    #_app.include_router(router=user, prefix="/v1/user", tags=["user"])
    _app.include_router(router=testcase, prefix="/v1/testcase", tags=["testcase"])
    _app.include_router(router=conversation, prefix="/v1/conversation", tags=["conversation"])
    _app.include_router(router=chat, prefix="/v1/chat", tags=["chat"])
    _app.include_router(router=file, prefix="/v1/file", tags=["file"])
    # 注册 mysql 数据源
    register_tortoise(
        _app,
        db_url=f"mysql://root:123456@localhost:3306/test?charset=utf8mb4&maxsize=20&minsize=5",
        modules={'models': ['entity.database.mysql']},  # 替换成你定义的模型路径
        generate_schemas=True,  # 若首次初始化需要建表可打开
        add_exception_handlers=True,
    )

    @_app.on_event("startup")
    async def app_startup():
        os.makedirs("logs", exist_ok=True)

        # 清除旧的 handler，防止重复添加
        for handler in logging.root.handlers[:]:
            logging.root.removeHandler(handler)

        logging.basicConfig(
            level=logging.INFO,
            format="%(asctime)s - %(levelname)s - %(message)s",
            handlers=[
                logging.FileHandler("logs/app.log", mode='a', encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        logging.info("fastapi run------------------ Starting")

    @_app.on_event("shutdown")
    async def shutdown_event():
        logging.info("fastapi run------------------ ending")

    return _app

app = create_app()  # 正式环境切换


if __name__ == '__main__':
    uvicorn.run("app:app",workers=8)
